import Vue, { ref }  from 'vue';
import dingtalk from '@src/util/dingtalk';
import FrameView from './FrameView.vue';
import { Notification } from 'element-ui';
import mtracker from '@src/util/mtracker';
import { Loading } from 'element-ui';
import { getAsyncSystemFrameInitData } from '@src/api/InitDataApi';
import qs from 'qs';
import platform from '@src/platform';
// import { getPcHomePageMenuList } from '@src/api/UserCenterApi.js';
import { getPcHomePageMenuListV2 } from '@src/api/UserCenterApi.js';
import platformExtension from '@src/platform/extension';
import { getRootWindow } from '@src/util/dom';
import { updateThemeColor } from './updateThemeColor';

import { isDevelopment } from '@src/util/platform';

/* tenant */
import { useTenantFetchProductLines, setProductLineDataByInitData } from '@shb-lib/tenant'
/* version */
import { useVersionFetchShbVersionControl } from '@src/modules/version'

window.onload = function () {
  window.Notification.requestPermission();
};
import VueTour from 'vue-tour';
import 'vue-tour/dist/vue-tour.css';
Vue.use(VueTour);

mtracker();

window.__exports__notification = Notification;
window.open_insideIM = platform.open_insideIM;
const componentItem = initData => {
  return {
    provide: {
      initData: Object.freeze(initData),
    },
    render(h) {
      return h(FrameView);
    },
  };
};

async function getInitData() {
  
  let query = qs.parse(window.location.search.substr(1));
  const params = Object.assign({}, query, {});
  let initData = {}
  
  try {
    
    const [result, {data}] = await Promise.all([getAsyncSystemFrameInitData(params), getPcHomePageMenuListV2()])

    // const result = await getAsyncSystemFrameInitData(params);
    initData = result?.data?.initJson || {};
    const title = (result && result.data && result.data.title) || '';
    document.title = title;
    const isSuccess = result.succ || result.success;
    const isProduction = process.env.NODE_ENV === 'production' || !isDevelopment();
    
    try {
      // 更新主题色和导航栏背景
      updateThemeColor(initData)
    } catch (error) {
      console.error(error)
    }
    /**
     * @description 如果是返回 PUB_VERSION 值
     * 则代表当前租户的cookie上的版本号 与 当前租户实际的版本号不一致
     * 需要更新 cookie 上的版本号，并且刷新页面
     */
    if (initData?.PUB_VERSION && isProduction) {
      document.cookie = `PUB_VERSION=${initData.PUB_VERSION};path=/;`;
      window.location.reload();
    }
    
    if (!isSuccess) {
      window.location.href = '/500';
      return;
    }
    
    // const { data } = await getPcHomePageMenuList();
    initData.barPageList = data.barPageList || [];
    initData.morePageList = data.morePageList || [];
    initData.showUploadTenantLogo = data.showUploadTenantLogo;
    initData.calendar = data.showCalendar;
    initData.notice = data.showNotice;
    
  } catch (error) {
    console.error('getPcHomePageMenuListV2 失败', error)
    window.location.href = '/500'
    return null
  }
  
  if (window.DingTalkPC) dingtalk.sign(initData.ddConfig);
  
  try {
    window._init = JSON.stringify(initData);
  } catch (error) {
    console.error('initData 赋值失败');
  }
  
  /** 
   * @description 产品线数据设置
  */
  try {
    setProductLineDataByInitData(initData)
  } catch (error) {
    console.error('设置产品线数据失败', error);
  }
  
  /** 
   * @description 获取版本控制数据
   * ?? 暂时先异步获取，后续有问题再改成同步
  */
  try {
    const { fetchPageElementsNumList } = useVersionFetchShbVersionControl()
    await fetchPageElementsNumList()
  } catch (error) {
    console.error('获取版本控制数据', error);
  }
  
  // 企微端需要在这里签名
  if (initData.tenantType == 2) {
    const rootWindow = getRootWindow(window);
    if (rootWindow.wxConfig) {
      // platformExtension.injectAuth(rootWindow.wxConfig)
    } else {
      try {
        await platformExtension.sign();
        eventBus.$emit('wx-sign-done');
      } catch (error) {
        console.warn('wx sign', error);
      }
    }
  }
  
  return initData;
  
}

let app = {
  components: {
    FrameView,
  },
  setup() {
    const initData = ref(null)
    const instance = Loading.service({ fullscreen: true });
    getInitData().then(res => {
      instance.close();
      initData.value = res;
    });
    
    return {
      initData,
    }
  },
  render(h) {
    return this.initData ? <frame-view initData={this.initData} /> : null;
  },
};

export default app;
